import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';

Page({
  data: {
    isHideen: false,
    avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0', // 默认头像
    nickname: '', // 默认昵称
    overlay: true,
    sessionId: '', // 用于存储后端返回的 sessionId，
    showDialog:false
    
   

  },

  onLoad() {
    wx.onThemeChange((result) => {
      this.setData({
        theme: result.theme
      });
    });

  
    // 尝试从本地存储中加载 session 信息
    const storedSession = wx.getStorageSync('sessionId');
    if (storedSession) {
      this.setData({
        sessionId: storedSession,
        HaisHideen:false
      });
      this.checkSession();
    }
  },

  getUserInfo() {
    wx.login({
      success: ({
        code
      }) => {
        if (code) {
          console.log(`Login code: ${code}`);
          wx.request({
            url: 'http://localhost:9001/wx/login', // 替换为你的后端接口地址
            method: 'POST',
            data: {
              code
            },
            withCredentials: true, 
            header: {
              'Content-Type': 'application/json'
            },
            success: (res) => {
              console.log('Login response:', res.data);

              if (res.data.data.sessionid) {
                // 保存 sessionId 到本地存储
                wx.setStorageSync('sessionId', res.data.data.sessionid);
                console.log(res.data.data.sessionid)
                this.setData({
                  sessionId: res.data.data.sessionid
                });

                if (this.data.nickname === '') {
                  Toast('请填入正确的头像和昵称！');
                } else {
                  this.setData({
                    isHideen: true,
                    overlay: false
                  });
                }
              } else {
                Toast('登录失败，请重试！');
              }
            },
            fail: () => {
              Toast('网络请求失败，请检查网络！');
            }
          });
        } else {
          Toast('登录失败，请重试！');
        }
      }
    });
  },

  checkSession() {
    const sessionId = this.data.sessionId;
    if (!sessionId) return;

    wx.request({
      url: 'http://localhost:9001/wx/checkSession', // 替换为你的后端接口地址
      method: 'POST',
      data: {
        sessionId
      },
      withCredentials: true, 
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('Session check response:', res.data);
        if (!res.data.valid) {
          // 如果 session 已失效，清除本地存储并提示用户重新登录
          wx.removeStorageSync('sessionId');
          this.setData({
            sessionId: ''
          });
          Toast('登录状态已过期，请重新登录！');
        }
      },
      fail: () => {
        Toast('无法验证登录状态，请检查网络！');
      }
    });
  },

  closeModal() {
    this.setData({
      isHideen: true,
      overlay: false
    });
  },

  getAvatar(e) {
    console.log(e);
    this.setData({
      avatarUrl: e.detail
    });
  },

  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail;
    console.log(avatarUrl);
    this.setData({
      avatarUrl,
    });
  },

  getNickname(e) {
    console.log(e);
    this.setData({
      nickname: e.detail.value
    });
    console.log(this.data.nickname);
  },

  logout() {
    wx.removeStorageSync('sessionId'); // 清除本地 sessionId
    this.setData({
      nickname: '',
      avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
      isHideen: false,
      overlay: true,
      sessionId: ''
    });
  },
  handleTap() {
    wx.getStorage({
      key: 'sessionId',
      success: (res) => {
        const cookie = `JSESSIONID=${res.data}`; // 确保 cookie 格式正确
        this.setData({ cookie });
  
        wx.request({
          url: 'http://localhost:9001/wx/isEmployee',
          method: 'GET',
          header: {
            'cookie': cookie
          },
          withCredentials: true, // 确保请求携带凭证
          success: (res) => {
            console.log('isEmployee 响应:', res.data);

            
            if (res.data.data == true) {

              wx.navigateTo({
                url: '/pages/receiving/receiving'
              });
            } else {
              wx.navigateTo({
               url: '/pages/certify/certify'
              });
            }
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
        });
      },
      fail: () => {
        console.error('sessionId 获取失败');
      }
    });
  }
  
});